import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as classNames from 'classnames';
import ProductInfo from "../models/ProductInfo";
import { List } from "immutable";

interface ProductItemProps {
  product: ProductInfo;
  index: number;
}

class ProductItem extends React.PureComponent<ProductItemProps, any> {
  constructor(props) {
    super(props)
    this.state = {
      mouseover: false
    }
  }

  static contextTypes = {
    addRow: React.PropTypes.func,
    deleteRow: React.PropTypes.func,
    editProduct: React.PropTypes.func
  }

  componentDidMount() {
    const self = this;
    $(ReactDOM.findDOMNode(this))
      .on("mouseenter", function () {
        self.setState({ mouseover: true })
      })
      .on("mouseleave", function () {
        self.setState({ mouseover: false })
      })
  }

  render() {
    const { product, index } = this.props;
    const { addRow, deleteRow, editProduct } = this.context;
    const { mouseover } = this.state;
    return (
      <tr className="productItem">
        <td className='textCenter'>
          <span id="orderdiv" className="num">{index + 1}</span>
          <span className="actionArea">
            <a href="javascript:;" title="增加行" className="plusLite" onClick={() => addRow(index)}></a>
            <a href="javascript:;" title="删除行" className="delLite" onClick={() => deleteRow(index)}></a>
          </span>
        </td>
        <td>
          <div className="choseGoodArea">
            <div className="proName1 fl mr5" style={{ width: "160px" }} title="ADFASFDFA">
              <input type="text"
                className="receiptsInputText"
                autoComplete="off"
                value={product.product_name || ""}
                onChange={(e) => editProduct(product, "product_name", e.target.value)} />
            </div>
            <a href="javascript:;" className={classNames("choseGoods", { hidden: !mouseover })}>选择</a>
          </div>
        </td>
        <td className='textCenter'>
          <input type="text"
            className="receiptsInputText"
            autoComplete="off"
            value={product.product_code || ""}
            onChange={(e) => editProduct(product, "product_code", e.target.value)} />
        </td>
        <td >
          <input type="text"
            className="receiptsInputText"
            autoComplete="off"
            value={product.product_price || ""}
            onChange={(e) => editProduct(product, "product_price", e.target.value)} />
        </td>
        <td className='textCenter'>
          <input type="text"
            className="receiptsInputText"
            autoComplete="off"
            value={product.product_count || ""}
            onChange={(e) => editProduct(product, "product_count", e.target.value)} />
        </td>
        <td className='textCenter'>
          <input type="text" className="receiptsInputText" name="UnitName" />
        </td>
        <td className='textCenter'>
          <input type="text " className="receiptsInputText" name="eachSaleAmt " autoComplete="off"
            value={product.eachSaleAmt || ""}
            onChange={(e) => editProduct(product, "eachSaleAmt", e.target.value)} />
        </td>
        <td className='textCenter'>
          <input style={{ textAlign: 'left' }} type="text" className="receiptsInputText"
            value={product.eachSaleRemark || ""}
            name="eachSaleRemark"
            onChange={(e) => editProduct(product, "eachSaleRemark", e.target.value)} />
        </td>
      </tr>
    )
  }
}

interface ProductGridProps {
  products: List<ProductInfo>;
}

export default class ProductGrid extends React.PureComponent<ProductGridProps, any> {

  tableInfoRef: React.ReactInstance;
  componentDidMount() {
    this.resizeContent();
  }

  resizeContent() {
    var totalWidth = 0;
    var colcount = 0;
    $(ReactDOM.findDOMNode(this.tableInfoRef)).find("th")
      .each(function (index, element) {
        colcount++;
        totalWidth = totalWidth + parseInt($(this).attr("data-width"));
      });

    if (totalWidth > document.body.clientWidth - 85) {
      $(".whiteBox").css("width", (document.body.clientWidth - 85) + "px");
    }
    else {
      const morewidth = document.body.clientWidth - 85 - totalWidth;
      const average = morewidth / colcount;
      $(ReactDOM.findDOMNode(this.tableInfoRef)).find("th")
        .each(function (index, element) {
          $(this).css("width", parseInt($(this).attr("data-width")) + average + "px");
        });
    }
  }

  render() {
    const products = this.props.products;
    console.log(products.toJS())
    return (
      <div>
        <table ref={ref => this.tableInfoRef = ref}
          style={{ width: "100%" }}
          cellSpacing="1"
          cellPadding="5"
          className="textCenter tableStyle">
          <tbody>
            <tr id="header">
              <th data-width="40" ><span className="textCenter normal">序号</span></th>
              <th data-width="200" className="normal">商品名称/规格</th>
              <th data-width="100" className="textCenter normal">商品编号</th>
              <th data-width="60" className="textCenter normal">单价(元)</th>
              <th data-width="70" className="textCenter normal" >数量</th>
              <th data-width="60" className="textCenter normal">单位</th>
              <th data-width="80" className="textCenter normal">金额(元)</th>
              <th data-width="70" className="textCenter normal">备注</th>
            </tr>
            {
              products.map((product, index) =>
                <ProductItem key={product.id}
                  product={product}
                  index={index}></ProductItem>
              )}
            <tr id="total">
              <td className="textCenter font14">合计</td>
              <td></td>
              <td></td>
              <td></td>
              <td className="textCenter">
                <span className="font16 fontRed">2</span>
              </td>
              <td ></td>
              <td className="textCenter">
                <span className="font16 fontRed">￥111
                </span>
              </td>
              <td ></td>
            </tr>
            <tr id="bottom">
              <td className="font14">备注</td>
              <td>
                <textarea
                  className="receiptsInputText textl"
                  cols={20}
                  id="SaleRemark"
                  name="SaleRemark" rows={2} style={{ height: '40px' }}></textarea>
              </td>
              <td colSpan={5}>

              </td>
              <td>
                <div className="font16 fontOrange" style={{ lineHeeight: '25px' }}>实收金额：</div>
                <input className="inputBorder"
                  data-val="true"
                  data-val-number="字段 ReceAmt 必须是一个数字。"
                  data-val-range="数值超出合理的范围"
                  data-val-range-max="9999999999" data-val-range-min="0"
                  data-val-regex="实收金额格式不正确。"
                  data-val-regex-pattern="^(-?\d+)(\.\d+)?$" id="ReceAmt" name="ReceAmt" size={10} type="text" defaultValue="0" />
              </td>
            </tr>
          </tbody>
        </table>
        <table cellSpacing="0" cellPadding="3">
          <tbody>
            <tr>
              <td>结算方式：</td>
              <td>
                <select
                  data-val="true"
                  data-val-required="请选择收款账户"
                  id="AccountId"
                  name="AccountId"
                  style={{ width: "100px" }}>
                  <option defaultValue="22bdd766-06f7-4fd6-bd7e-e3a176d98c0b">现金</option>
                </select>
              </td>
            </tr>
            <tr>
              <td style={{ width: '100px' }}>折 扣 率：</td>
              <td style={{ width: '110px' }}>
                <input className="inputBorder"
                  data-val="true"
                  data-val-number="字段 DiscountRate 必须是一个数字。"
                  data-val-range="数值超出合理的范围"
                  data-val-range-max="9999999999"
                  data-val-range-min="0"
                  data-val-regex="折扣率格式不正确。"
                  data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                  id="DiscountRate"
                  name="DiscountRate"
                  size={8} type="text" defaultValue="100" />%
                                  </td>
              <td style={{ width: "60px" }}>折后应收：</td>
              <td>
                <input
                  className="inputBorder"
                  data-val="true"
                  data-val-number="字段 DiscountAmt 必须是一个数字。"
                  data-val-range="数值超出合理的范围"
                  data-val-range-max="9999999999"
                  data-val-range-min="0"
                  data-val-regex="折后应收金额格式不正确。"
                  data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                  id="DiscountAmt"
                  name="DiscountAmt"
                  size={8} type="text" defaultValue="0" />                                                                                元
                       </td>
            </tr>
            <tr>
              <td>其他费用：</td>
              <td>
                <input
                  className="inputBorder"
                  data-val="true"
                  data-val-number="字段 OtherFee 必须是一个数字。"
                  data-val-regex="其他费用格式不正确。"
                  data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                  data-val-required="请输入本次其他费用" id="OtherFee"
                  name="OtherFee"
                  size={8}
                  type="text" defaultValue="0" />元
                                  </td>
              <td >应收金额：</td>
              <td>
                <span id="spanFAReceAmt">0</span>
                <input
                  data-val="true"
                  data-val-number="字段 FAReceAmt 必须是一个数字。"
                  data-val-range="数值超出合理的范围"
                  data-val-range-max="9999999999"
                  data-val-range-min="0"
                  data-val-regex="折后应收金额格式不正确。" data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                  id="FAReceAmt"
                  name="FAReceAmt" type="hidden" defaultValue="0" />元
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    )
  }
}